package main

import (
	"context"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"bsm/config"
	"bsm/daos"
	"bsm/logger"
	"bsm/routes"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func init() {
	// 设置 Gin 为发布模式
	gin.SetMode(gin.ReleaseMode)

	// 日志自动选择级别
	if err := logger.Init(""); err != nil {
		panic(err)
	}

	err := godotenv.Load()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "main",
			"operation": "init",
		}).Errorf("加载配置文件失败: %v", err)

		os.Exit(1)
	}
	config.Init()
}

func main() {
	if err := daos.InitRedis(); err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "main",
			"operation": "init",
		}).Warnf("Redis初始化失败: %v", err)
		logger.WithFields(map[string]interface{}{
			"layer":     "main",
			"operation": "init",
		}).Info("应用程序将在降级模式下运行（无Redis支持）")
	}

	dbBSD, dbSCM, err := daos.InitDatabase()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "main",
			"operation": "init",
		}).Errorf("初始化数据库失败: %v", err)
		os.Exit(1)
	}
	defer dbBSD.Close()
	defer dbSCM.Close()

	defer daos.CloseRedisClient()

	// 创建路由
	r := gin.New()
	r.Use(cors.Default())
	routes.RegisterRoutes(r, dbBSD, dbSCM)

	// 创建优雅关闭的信号监听
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	srv := &http.Server{
		Addr:    ":" + config.Get().AppConfig.ServerPort,
		Handler: r,
	}

	go func() {
		logger.WithFields(map[string]interface{}{
			"layer":     "main",
			"operation": "run",
		}).Infof("服务器启动在端口 %s", config.Get().AppConfig.ServerPort)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.WithFields(map[string]interface{}{
				"layer":     "main",
				"operation": "run",
			}).Errorf("启动服务器失败: %v", err)
			os.Exit(1)
		}
	}()

	// 等待中断信号
	<-quit
	logger.WithFields(map[string]interface{}{
		"layer":     "main",
		"operation": "run",
	}).Info("正在关闭服务器...")

	// 设置优雅关闭的超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "main",
			"operation": "run",
		}).Errorf("服务器强制关闭: %v", err)
		os.Exit(1)
	}

	logger.WithFields(map[string]interface{}{
		"layer":     "main",
		"operation": "run",
	}).Info("服务器已退出")
}
